package org.madmac.ip;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.madmac.exception.IpNotFoundException;
import org.wakeful.conn.Connection;

public class IpDao {

   private static IpDao instance;
   /**
    * @deprecated 
    */
   private String ip_livre;

   private IpDao() {
   }

   public String getIp_livre() {
      return ip_livre;
   }

   public void setIp_livre(String ip_livre) {
      this.ip_livre = ip_livre;
   }

   public static IpDao getInstance() {
      if (instance == null) {
         instance = new IpDao();
      }
      return instance;
   }

   /**
    * 
    * @return
    * @throws SQLException
    * @throws ClassNotFoundException
    * @throws Exception
    * @deprecated Use FaixaIpDAO.getInstance().selectLastIp()
    */
   public Ip selectMaxIp() throws SQLException, ClassNotFoundException, Exception {

      Ip search_ip = null;
      java.sql.Connection conn = Connection.getInstance();
      Statement stmt = conn.createStatement();
      /**
       * consertar!
       * este método não esta sendo usado e sim o da classe FaixaIpDAO !
       */
      String sql = "SELECT MAX(ip) FROM madmac.ip WHERE livre = 'true' ";

      ResultSet rs = null;
      try {
         rs = stmt.executeQuery(sql);
      } catch (Exception e) {

         return null;
      }

      if (rs.next()) {

         search_ip = new Ip();
         String ip = rs.getString("ip");
         search_ip.setIp(ip);
      } else {
         throw new IpNotFoundException();
      }
      return search_ip;
   }

   public String selectIpLivre(int idFaixaIp) throws SQLException, ClassNotFoundException, Exception {

      String searchIp = null;
      java.sql.Connection conn = Connection.getInstance();
      PreparedStatement pstmt = conn.prepareStatement(IpQuery.selectIpLivre());
      pstmt.setInt(1, idFaixaIp);

      ResultSet rs = null;
      try {
         rs = pstmt.executeQuery();

         if (rs.next()) {
            searchIp = rs.getString("ip_livre");
         } else {
            throw new IpNotFoundException();
         }
      } catch (Exception e) {
         throw new Exception(e);
      } finally {
         pstmt.close();
         if (rs != null) {
            rs.close();
         }
      }
      return searchIp;
   }

   public String pingHost(String host) {

      String resposta = "";



      return resposta;
   }
}
